package com.qf.service;

import com.qf.dao.TenderInformationMapper;
import com.qf.pojo.TenderInformation;
import com.qf.util.ContentExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger; // 新增导入

@Service
public class TenderInfoUpdateService {

    private static final Logger logger = LoggerFactory.getLogger(TenderInfoUpdateService.class);

    @Autowired
    private TenderInformationMapper tenderInformationMapper;

    public void batchUpdateFields() {
        // 查询所有ID
        List<Integer> idList = tenderInformationMapper.getAllIds();
        logger.info("开始处理招标信息提取，总记录数: {}", idList.size());

        // 使用线程安全的计数器
        AtomicInteger updatedCount = new AtomicInteger(0);
        AtomicInteger phoneFixedCount = new AtomicInteger(0); // 修复电话计数

        for (Integer id : idList) {
            try {
                // 传递计数器给处理方法
                boolean result = processSingleRecord(id, phoneFixedCount);
                if (result) {
                    updatedCount.incrementAndGet();
                }
            } catch (Exception e) {
                logger.error("处理记录失败，ID: {}, 错误: {}", id, e.getMessage());
            }

            // 每处理100条记录输出一次进度
            int processed = updatedCount.get() + phoneFixedCount.get();
            if (processed % 100 == 0 && processed > 0) {
                logger.info("处理进度: {}/{}", processed, idList.size());
            }
        }

        logger.info("招标信息提取处理完成");
        logger.info("成功更新 {} 条记录，修复 {} 个无效电话", updatedCount.get(), phoneFixedCount.get());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    protected boolean processSingleRecord(Integer id, AtomicInteger phoneFixedCount) { // 添加参数
        // 1. 查询整个记录（避免多次查询）
        TenderInformation original = tenderInformationMapper.selectById(id);
        if (original == null || original.getBusinessContentText() == null) {
            return false;
        }

        String content = original.getBusinessContentText();
        if (content.isEmpty()) {
            return false;
        }

        // 2. 提取信息
        String newContact = ContentExtractor.extractContact(content);
        String newPhone = ContentExtractor.extractPhone(content);
        String newPrice = ContentExtractor.extractPrice(content);

        // 3. 检查是否需要更新
        boolean needsUpdate = false;
        TenderInformation updateItem = new TenderInformation();
        updateItem.setId(id);

        // 联系人：总是更新
        if (!Objects.equals(original.getContactPerson(), newContact)) {
            updateItem.setContactPerson(newContact);
            needsUpdate = true;
        }

        // 电话：只更新有效电话
        // 修复括号问题：在 ContentExtractor.isValidPhone(newPhone) 后面添加右括号
        if (newPhone != null && ContentExtractor.isValidPhone(newPhone) &&
                !Objects.equals(original.getPhone(), newPhone)) {
            updateItem.setPhone(newPhone);
            needsUpdate = true;

            // 如果原始电话无效但新电话有效，计数为修复
            if (!ContentExtractor.isValidPhone(original.getPhone())) { // 这里添加了右括号
                phoneFixedCount.incrementAndGet(); // 使用原子计数器
            }
        }

        // 价格：总是更新
        if (!Objects.equals(original.getPrice(), newPrice)) {
            updateItem.setPrice(newPrice);
            needsUpdate = true;
        }

        // 4. 如果有变化则更新
        if (needsUpdate) {
            tenderInformationMapper.updateById(updateItem);
            return true;
        }

        return false;
    }
}